<template>
  <div>
    <van-cell v-for="(item, index) in suggestions" :key="index" icon="search">
      <div @click='$emit("search", item)' slot='title' v-html="textAction(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSesrchSuggestion } from '@/api/search.js'
import { debounce } from 'lodash'
export default {
  data () {
    return {
      suggestions: ''
    }
  },
  props: {
    searchTxt: {
      type: String,
      required: true
    }
  },
  watch: {
    searchTxt: {
      // 立即执行
      immediate: true,
      handler: debounce(function () {
        this.loadSuggestions()
      }, 1000)
    }
  },
  created () {

  },

  methods: {
    async loadSuggestions () {
      try {
        const { data: res } = await getSesrchSuggestion(this.searchTxt)
        this.suggestions = res.data.options
      } catch (error) {
        this.$toast('获取联想建议失败!')
      }
    },
    textAction (str) {
      const reg = new RegExp(this.searchTxt, 'gi')
      str = str.replace(reg, '<span style="color: red">' + this.searchTxt + '</span>')
      return str
    }
  }
}
</script>

<style scoped lang='less'>

</style>
